package flyingpig.servlet;

import java.io.IOException;
import java.util.Date;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import com.thoughtworks.xstream.XStream;

import flyingpig.data.dao.JobPageHome;
import flyingpig.data.domain.JobPage;
import flyingpig.hibernate.HibernateUtil;


public class RequestJobPage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private   static   Log   logger   =   LogFactory.getLog(RequestJobPage.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestJobPage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
		int searchJobID = -1;
		try{
			searchJobID = Integer.parseInt(request.getParameter("searchJobID"));
		}catch(Exception e){
			// do nothing
		}
		logger.info("receive jobrequest  searchJobId = " + searchJobID);
		
		JobPage page = getOnePage(searchJobID);

		if (page == null) {
			logger.info("no jobpage available");
			response.getOutputStream().println("status: no jobPage available");
		} else {
			logger.info("return jobpage, searchJobId:" + page.getSearchJobId()
					+ ", page:" + page.getPage());
			// Xstream xml
			XStream xs = new XStream();
			xs.alias("JobPage", JobPage.class);
			xs.toXML(page, response.getOutputStream());
		}

		response.getOutputStream().flush();
		response.getOutputStream().close();

	}
	
	synchronized private JobPage getOnePage(int searchJobID) {
		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		JobPage page = null;
		try {
		

		JobPageHome jobPageDao = new JobPageHome();
		page = jobPageDao.findOnePageBySearchJobID(searchJobID);
		if (page != null) {
			page.setPageState("DOWNLOADING");
			page.setLastUpdate(new Date());
			jobPageDao.persist(page);
		}
		tx.commit();
		}catch (HibernateException e) {
			tx.rollback();
		}

		return page;
	}
}
